package com.windowes.weichang.service;

import com.baomidou.mybatisplus.plugins.Page;
import com.windowes.weichang.access.UserContext;
import com.windowes.weichang.common.ServerResponse;
import com.windowes.weichang.dao.SysDeptRelationMapper;
import com.windowes.weichang.dao.SysRoleDeptMapper;
import com.windowes.weichang.dao.SysRoleMapper;
import com.windowes.weichang.pojo.SysDeptRelationKey;
import com.windowes.weichang.pojo.SysRole;
import com.windowes.weichang.pojo.SysRoleDept;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/***
 *
 * @author: yangqing
 * @email: qing.yang@bangdao-tech.com
 * @createTime: 2018/7/28 下午8:32
 * @description:
 *
 **/
@Service
public class RoleService {

    @Autowired
    SysRoleMapper sysRoleMapper;
    @Autowired
    SysRoleDeptMapper sysRoleDeptMapper;
    @Autowired
    SysDeptRelationMapper sysDeptRelationMapper;


    /**
     * 添加角色
     *
     * @param sysRole
     * @return
     */
    public ServerResponse addOrUpdate(SysRole sysRole) {
        if (StringUtils.isBlank(sysRole.getRoleCode())) {
            return ServerResponse.createByErrorMessage("请设置角色代码!");
        }

        if (StringUtils.isBlank(sysRole.getRoleName())) {
            return ServerResponse.createByErrorMessage("请设置角色名称!");
        }


        Integer deptId = UserContext.getDeptId();

        if (sysRole.getRoleId() == null) {
            sysRoleMapper.insertSelective(sysRole);
            SysRoleDept roleDept = new SysRoleDept();
            roleDept.setDeptId(deptId);
            roleDept.setRoleId(sysRole.getRoleId());
            sysRoleDeptMapper.insertSelective(roleDept);
        } else {
            sysRoleMapper.updateByPrimaryKeySelective(sysRole);

        }
        return ServerResponse.createBySuccessMessage("操作成功");
    }


    /**
     * 获取角色列表
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    public ServerResponse list(int pageNo, int pageSize) {
        Integer deptId = UserContext.getDeptId();
        Page<SysRole> page = new Page<>(pageNo, pageSize);
        page.setRecords(sysRoleMapper.selectByPage(deptId, page));
        return ServerResponse.createBySuccess(page);
    }

    private List<Integer> buildDeptIds(Integer deptId) {
        //获取当前部门的子部门
        SysDeptRelationKey deptRelation = new SysDeptRelationKey();
        deptRelation.setAncestor(deptId);
        List<SysDeptRelationKey> deptRelationList = sysDeptRelationMapper.selectList(deptRelation);
        List<Integer> deptIds = new ArrayList<>();
        for (SysDeptRelationKey sysDeptRelation : deptRelationList) {
            deptIds.add(sysDeptRelation.getDescendant());
        }
        return deptIds;
    }
}
